import 'package:dio/dio.dart';
import '../core/api_client.dart';
import '../core/api_response.dart';
import '../core/api_logger.dart';
import '../models/love_quote.dart';

class LoveQuoteService {
  final ApiClient _apiClient;
  
  LoveQuoteService({ApiClient? apiClient}) 
      : _apiClient = apiClient ?? ApiClient();

  Future<ApiResponse<List<LoveQuote>>> getAllQuotes() async {
    // 获取所有情话列表
    try {
      final response = await _apiClient.get('/api/quotes');
      
      final List<LoveQuote> quotes = (response.data as List)
          .map((json) => LoveQuote.fromJson(json))
          .toList();
          
      // 成功获取情话列表
      return ApiResponse.success(
        data: quotes,
        message: '获取情话列表成功',
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      // 获取情话列表失败
      return _handleDioError(e);
    } catch (e) {
      // 未知错误处理
      return ApiResponse.error(
        error: '获取情话列表失败: $e',
        statusCode: 500,
      );
    }
  }

  Future<ApiResponse<LoveQuote>> getQuoteById(int id) async {
    try {
      final response = await _apiClient.get('/api/quotes/$id');
      
      final quote = LoveQuote.fromJson(response.data);
          
      return ApiResponse.success(
        data: quote,
        message: '获取情话详情成功',
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      return _handleDioError(e);
    } catch (e) {
      return ApiResponse.error(
        error: '获取情话详情失败: $e',
        statusCode: 500,
      );
    }
  }

  Future<ApiResponse<bool>> createQuote(LoveQuote quote) async {
    try {
      final response = await _apiClient.post(
        '/api/quotes',
        data: quote.toJson(),
      );
      
      return ApiResponse.success(
        data: response.data == true,
        message: '创建情话成功',
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      return _handleDioError(e);
    } catch (e) {
      return ApiResponse.error(
        error: '创建情话失败: $e',
        statusCode: 500,
      );
    }
  }

  Future<ApiResponse<bool>> updateQuote(int id, LoveQuote quote) async {
    try {
      final response = await _apiClient.put(
        '/api/quotes/$id',
        data: quote.toJson(),
      );
      
      return ApiResponse.success(
        data: response.data == true,
        message: '更新情话成功',
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      return _handleDioError(e);
    } catch (e) {
      return ApiResponse.error(
        error: '更新情话失败: $e',
        statusCode: 500,
      );
    }
  }

  Future<ApiResponse<bool>> deleteQuote(int id) async {
    try {
      final response = await _apiClient.delete('/api/quotes/$id');
      
      return ApiResponse.success(
        data: response.data == true,
        message: '删除情话成功',
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      return _handleDioError(e);
    } catch (e) {
      return ApiResponse.error(
        error: '删除情话失败: $e',
        statusCode: 500,
      );
    }
  }

  Future<ApiResponse<LoveQuote>> getRandomQuote({
    String? category,
    String? moodTag,
    List<String>? excludeIds,
    int? maxLength,
    int? minLength,
  }) async {
    ApiLogger.logLoveQuoteRequest();
    
    try {
      // 构建查询参数
      Map<String, dynamic>? queryParams = _buildRandomQuoteParams(
        category: category,
        moodTag: moodTag,
        excludeIds: excludeIds,
        maxLength: maxLength,
        minLength: minLength,
      );
      
      // 记录请求参数（生产环境中省略）
      
      final response = await _apiClient.get(
        '/api/quotes/random',
        queryParameters: queryParams,
      );
      
      // 验证响应数据
      if (response.data == null) {
        ApiLogger.logLoveQuoteError('接口返回空数据');
        return _getRandomDefaultQuote();
      }
      
      final quote = LoveQuote.fromJson(response.data);
      
      ApiLogger.logLoveQuoteSuccess('${quote.content.substring(0, quote.content.length.clamp(0, 20))}...');
      
      // 增加使用计数
      if (quote.id != null) {
        _incrementQuoteUsage(quote.id!);
      }
      
      return ApiResponse.success(
        data: quote,
        message: '获取随机情话成功',
        statusCode: response.statusCode ?? 200,
      );
    } on DioException catch (e) {
      ApiLogger.logLoveQuoteError('${e.type} - ${e.message}');
      
      // 网络错误时返回缓存或默认情话
      return _getRandomDefaultQuote();
    } catch (e) {
      ApiLogger.logLoveQuoteError('未知错误: $e');
      
      return ApiResponse.error(
        error: '获取随机情话失败: $e',
        statusCode: 500,
      );
    }
  }

  Future<ApiResponse<LoveQuote>> getDailyQuote() async {
    ApiLogger.logLoveQuoteRequest();
    
    try {
      // 直接调用随机情话接口获取每日情话
      return await getRandomQuote(category: 'daily');
    } catch (e) {
      ApiLogger.logLoveQuoteError('获取每日情话失败: $e');
      return _getDefaultDailyQuote();
    }
  }

  ApiResponse<LoveQuote> _getDefaultDailyQuote() {
    final quotes = [
      '你是我心中最亮的星星 ⭐',
      '和你在一起的每一天都是最好的一天 💕',
      '你的笑容是我最喜欢的风景 😊',
      '爱你不是三分钟热度，而是深思熟虑后的决定 💖',
      '你是我的小确幸，也是我的大梦想 🌟',
      '想和你一起慢慢变老 👫',
      '你是我的今天，也是我所有的明天 🌅',
      '遇见你是我最美丽的意外 🎁',
    ];
    
    final today = DateTime.now();
    final index = (today.year + today.month + today.day) % quotes.length;
    final selectedQuote = quotes[index];
    
    // 使用统一的日志工具记录后备情话
    ApiLogger.logFallbackQuote(selectedQuote);
    
    final quote = LoveQuote(
      id: index + 1,
      content: selectedQuote,
      category: 'daily',
      language: 'zh_CN',
      moodTags: '爱情,甜蜜',
      usageCount: 1,
      isActive: 1,
      createdBy: 'system',
      createdAt: DateTime.now().millisecondsSinceEpoch,
    );
    
    return ApiResponse.success(
      data: quote,
      message: '获取每日情话成功（默认）',
    );
  }

  Map<String, dynamic>? _buildRandomQuoteParams({
    String? category,
    String? moodTag,
    List<String>? excludeIds,
    int? maxLength,
    int? minLength,
  }) {
    if (category == null && 
        moodTag == null && 
        excludeIds == null && 
        maxLength == null && 
        minLength == null) {
      return null;
    }

    final params = <String, dynamic>{};
    
    if (category != null && category.trim().isNotEmpty) {
      params['category'] = category.trim();
    }
    
    if (moodTag != null && moodTag.trim().isNotEmpty) {
      params['moodTag'] = moodTag.trim();
    }
    
    if (excludeIds != null && excludeIds.isNotEmpty) {
      params['excludeIds'] = excludeIds.join(',');
    }
    
    if (maxLength != null && maxLength > 0) {
      params['maxLength'] = maxLength;
    }
    
    if (minLength != null && minLength > 0) {
      params['minLength'] = minLength;
      
      // 确保 minLength <= maxLength
      if (maxLength != null && minLength > maxLength) {
        params['minLength'] = maxLength;
      }
    }
    
    return params.isEmpty ? null : params;
  }

  ApiResponse<LoveQuote> _getRandomDefaultQuote() {
    final quotes = [
      '你是我心中最亮的星星 ⭐',
      '和你在一起的每一天都是最好的一天 💕',
      '你的笑容是我最喜欢的风景 😊',
      '爱你不是三分钟热度，而是深思熟虑后的决定 💖',
      '你是我的小确幸，也是我的大梦想 🌟',
      '想和你一起慢慢变老 👫',
      '你是我的今天，也是我所有的明天 🌅',
      '遇见你是我最美丽的意外 🎁',
      '每天看到你的第一眼，就知道这将是美好的一天 ☀️',
      '爱情不是寻找一个完美的人，而是用完美的眼光去看待一个不完美的人 👀',
      '你在我身边就是岁月静好 🕊️',
      '想和你一起去看世界上所有的风景 🌍',
    ];
    
    // 使用随机数而不是日期，确保真正随机
    final random = DateTime.now().microsecondsSinceEpoch % quotes.length;
    final selectedQuote = quotes[random];
    
    ApiLogger.logFallbackQuote(selectedQuote);
    
    final quote = LoveQuote(
      id: random + 1,
      content: selectedQuote,
      category: 'random',
      language: 'zh_CN',
      moodTags: '爱情,甜蜜,温暖',
      usageCount: 1,
      isActive: 1,
      createdBy: 'system',
      createdAt: DateTime.now().millisecondsSinceEpoch,
    );
    
    return ApiResponse.success(
      data: quote,
      message: '获取随机情话成功（默认）',
    );
  }

  void _incrementQuoteUsage(int quoteId) {
    // 异步更新使用计数，不阻塞主流程
    Future.microtask(() async {
      try {
        await _apiClient.post('/api/quotes/$quoteId/increment');
        // 在调试模式下记录使用计数更新
        // 使用计数更新成功
      } catch (e) {
        // 静默处理使用计数更新失败，不影响用户体验
      }
    });
  }

  ApiResponse<T> _handleDioError<T>(DioException error) {
    String message;
    int statusCode = error.response?.statusCode ?? 500;
    
    switch (error.type) {
      case DioExceptionType.connectionTimeout:
        message = '连接超时';
        break;
      case DioExceptionType.sendTimeout:
        message = '发送超时';
        break;
      case DioExceptionType.receiveTimeout:
        message = '接收超时';
        break;
      case DioExceptionType.badResponse:
        message = '服务器响应错误: ${error.response?.statusMessage}';
        break;
      case DioExceptionType.cancel:
        message = '请求已取消';
        break;
      case DioExceptionType.connectionError:
        message = '网络连接错误';
        break;
      case DioExceptionType.unknown:
      default:
        message = '未知网络错误: ${error.message}';
        break;
    }
    
    return ApiResponse.error(
      error: message,
      statusCode: statusCode,
    );
  }
}